package screen
{
	import com.adobe.serialization.json.JSON;
	import com.greensock.TweenLite;
	import com.greensock.easing.Quart;
	import com.pblabs.engine.PBE;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.setInterval;
	import flash.utils.setTimeout;
	
	import helper.Services;
	import helper.ValueObject;
	
	import screen.component.Ama;
	import screen.component.GetReward;
	import screen.component.Guide;
	import screen.component.HayCafe;
	import screen.component.Header;
	import screen.component.Home;
	import screen.component.Iris;
	import screen.component.Kico;
	import screen.component.Mission;
	import screen.component.Places;
	import screen.component.PreSchool;
	import screen.component.Rank;
	import screen.component.Resource;
	import screen.component.Restaurant;
	import screen.component.Supermarket;
	import screen.component.SupperFamily;
	import screen.component.TiniWorld;
	import screen.component.UI;
	import screen.component.Xcream;
	
	public class SacombankScreen extends UI
	{
		private var _bg:MovieClip;
		private var _current_place_no:Number=0;
		private var _place_width:Number;
		private var _mission_cl:Mission;
		private var _header_cl : Header;
		private var _rank_cl:Rank;
		private var _guide_cl: Guide;
		private var _control_right_mc:MovieClip;
		private var _control_footer_mc:MovieClip;
		private var _pig:MovieClip;
		private var _get_reward:MovieClip;
		private var _get_deposit:MovieClip;
		private var _place_group:MovieClip;
		private var _place_arr:Array=[];
		private var _place_name_arr:Array=[];
		private var _service:Services;
		private var _get_limit_time_loader:URLLoader;
		private var _remain_time:Number;
		private var _timer:Timer;
		private var _control_left_mc:MovieClip;
		private var _resource_user:Resource;
		private var _reward : GetReward;
		private var _ping_loader:URLLoader;
		private var _sound_btn:MovieClip;
		public static var instance:SacombankScreen;
		public static const SOUND_THEME:String = "bg";
		public function SacombankScreen()
		{
			if(!instance){
				instance = this;
			}
		}
		public static function getInstance():SacombankScreen{
			if(!instance){
				instance = new SacombankScreen();
			}
			return instance;
		}
		public function onShow():void {
			init();
			addSound(SOUND_THEME,9999);
			volumeSound(SOUND_THEME,1);
		}
		public function onHide():void{
			
		}
		private function init():void{
			_bg = ValueObject.S1_RESOURCE.getExportedAsset("backGround") as MovieClip;
			addChild(_bg);
			_mission_cl = new Mission();
			_header_cl = new Header();
			addChild(_header_cl)
			_guide_cl = new Guide();
			addChild(_mission_cl);
			_rank_cl = new Rank();
			addChild(_rank_cl);
			
			_place_group = new MovieClip;
			_place_arr =[new Home(),new Iris(),new PreSchool(),new Xcream(),new Restaurant(),new Ama(),new TiniWorld(),new Supermarket(),new HayCafe(),new Kico(),new SupperFamily()];
			_place_name_arr = ["home","iris","preSchool","xcream","restaurant","ama","tiniWorld","superMarket","hayCafe","kico","superFamily"];
			var leng:Number = _place_arr.length;
			_place_width = ValueObject.WIDTH;
			for(var i:Number=0;i<leng;i++){
				_place_arr[i].x =i*_place_width;
				_place_group.addChild(_place_arr[i]);
			}
			addChild(_place_group);
			
			_control_right_mc = ValueObject.S1_RESOURCE.getExportedAsset("controlRight") as MovieClip;
			with(_control_right_mc){
				buttonImageInit(rankBtn);
				MovieClip(rankBtn).addEventListener(MouseEvent.CLICK,showRankPopup);
				buttonImageInit(missionBtn);
				MovieClip(missionBtn).addEventListener(MouseEvent.CLICK,showMissionPopup);
			}
			addChild(_control_right_mc);
			
			_get_deposit = ValueObject.S2_RESOURCE.getExportedAsset("header") as MovieClip;
			with (_get_deposit) {
				buttonImageInit(exitBtn);	
				buttonImageInit(introBtn);
				buttonImageInit(babyBtn);
				buttonImageInit(homeBtn);
				MovieClip(exitBtn).addEventListener(MouseEvent.CLICK, showDepositPopup);
				MovieClip((introBtn)).addEventListener(MouseEvent.CLICK, gotoIntro);
				MovieClip(babyBtn).addEventListener(MouseEvent.CLICK, gotoBaby);
				MovieClip(homeBtn).addEventListener(MouseEvent.CLICK, goHome);
			}
			 addChild(_get_deposit);
			
			_reward = GetReward.getInstance();
			
			_control_left_mc = ValueObject.S2_RESOURCE.getExportedAsset("controlLeft") as MovieClip;
			with(_control_left_mc){
				buttonImageInit(resourceBtn);
				buttonImageInit(guideBtn);
				buttonImageInit(theleBtn);
				MovieClip(guideBtn).addEventListener(MouseEvent.CLICK, showGuidePopup);
				MovieClip(theleBtn).addEventListener(MouseEvent.CLICK, showThelePopup);
			}
			addChild(_control_left_mc);
			_resource_user = Resource.getInstance();
			
			 _pig = ValueObject.S1_RESOURCE.getExportedAsset("pig") as MovieClip;
			 _pig.gotoAndStop("one");
			 addChild(_pig);
			 
			_control_footer_mc = ValueObject.S1_RESOURCE.getExportedAsset("controlFooter") as MovieClip;
			var leng2:Number = _place_name_arr.length;
			for(var j:Number =0;j<leng;j++){
				var mc:MovieClip = _control_footer_mc.getChildByName(_place_name_arr[j]) as MovieClip;
				buttonImageInit(mc);
				mc.no= j;
				mc.addEventListener(MouseEvent.CLICK,sliderPlace);
				
			}
			addChild(_control_footer_mc);
			_get_limit_time_loader = new URLLoader();
			_service = Services.getInstance();
			_timer = new Timer(1000);
			getLimitTime();
			
			_sound_btn = ValueObject.S2_RESOURCE.getExportedAsset("soundBtn") as MovieClip;
			_sound_btn.gotoAndStop(1);
			_sound_btn.buttonMode = true;
			_sound_btn.addEventListener(MouseEvent.CLICK,soundClick);
			addChild(_sound_btn);
			
			resize();
			this.stage.addEventListener(Event.RESIZE, resize);
			
			_ping_loader = new URLLoader();
			pingService();
			var intervalId:uint = setInterval(pingService, 10000); 
			var intervalId2:uint = setInterval(pigTalk, 60000);
		}
		private function pingService():void {
			_ping_loader.load(_service.pingRequest());
		}
		private function pigTalk():void {
			_pig.gotoAndStop("two");
			setTimeout(nomalPig, 5000);
		}
		private function nomalPig():void {
			_pig.gotoAndStop("one");
		}
		
		private function resize(e:Event=null):void{
			ValueObject.WIDTH = this.stage.stageWidth;
			ValueObject.HEIGHT = this.stage.stageHeight;
			
			_control_right_mc.x = ValueObject.WIDTH ;
			_control_right_mc.y = 150;
			
			_control_left_mc.x = 0;
			_control_left_mc.y = 150;
			
			_control_footer_mc.x =0;
			_control_footer_mc.y = ValueObject.HEIGHT+30;
			
			_pig.x = 200;
			_pig.y = ValueObject.HEIGHT -140;
			
			_get_deposit.x = 0;
			_get_deposit.y = 0;
			
			_sound_btn.x =  ValueObject.WIDTH - 30;
			_sound_btn.y = 30;
			
			var leng:Number = _place_arr.length;
			_place_width = ValueObject.WIDTH;
			for(var i:Number=0;i<leng;i++){
				_place_arr[i].x =i*_place_width;
			}
			
		}
		private function getLimitTime():void{
			_get_limit_time_loader.addEventListener(Event.COMPLETE,getLimitTimeComplete);
			_get_limit_time_loader.addEventListener(IOErrorEvent.IO_ERROR,getLimitTiomeError);
			_get_limit_time_loader.load(_service.getLimitTimeRequest());
		}
		private function getLimitTimeComplete(e:Event):void{
			_get_limit_time_loader.removeEventListener(Event.COMPLETE,getLimitTimeComplete);
			_get_limit_time_loader.removeEventListener(IOErrorEvent.IO_ERROR,getLimitTiomeError);
			var ob:Object = JSON.decode(e.target.data);
			TextField(_control_right_mc.limitTf).text = ob.limit + "h";
			_remain_time = ob.left;
			if (_remain_time == 0) {
				_header_cl.showDepositPopup("Đã hết thời gian chơi!");
			}else {
				var hh:Number =Math.floor(_remain_time/3600);
				var mm:Number = Math.floor((_remain_time - hh*3600)/60);
				var ss:Number = _remain_time - hh*3600 - mm*60;
				TextField(_control_right_mc.remainTf).text = formatNumber(hh) +":"+formatNumber(mm)+":"+formatNumber(ss);
				_timer.addEventListener(TimerEvent.TIMER,timerHandle);
				_timer.start();
			}
			
		}
		private function getLimitTiomeError(e:IOErrorEvent):void{
			_get_limit_time_loader.removeEventListener(Event.COMPLETE,getLimitTimeComplete);
			_get_limit_time_loader.removeEventListener(IOErrorEvent.IO_ERROR,getLimitTiomeError);
			trace("getLimitTiomeError");
		}
		private function showMissionPopup(e:MouseEvent):void{
			_mission_cl.showMissionPopup();
			_rank_cl.closeHandle();
		}
		private function showDepositPopup(e:MouseEvent):void {
			_header_cl.showDepositPopup("");
			_rank_cl.closeHandle();
		}
		
		private function gotoIntro(e:MouseEvent):void {
			_header_cl.gotoIntro();
			_rank_cl.closeHandle();
		}
		
		private function gotoBaby(e:MouseEvent):void {
			_header_cl.gotoBaby();
			_rank_cl.closeHandle();
		}
		
		private function goHome(e:MouseEvent):void {
			_header_cl.goHome();
			_rank_cl.closeHandle();
		}
		
		private function showRankPopup(e:MouseEvent):void{
			_rank_cl.showRank();
			_mission_cl.hideMissionPopup();
		}
		
		private function showGuidePopup(e:MouseEvent):void {
			_guide_cl.showGuidePopup();
			_rank_cl.closeHandle();
		}
		private function showThelePopup(e:MouseEvent):void {
			_guide_cl.showThelePopup();
			_rank_cl.closeHandle();
		}		
		public function sliderPlace(e:MouseEvent):void{
			_rank_cl.closeHandle();
			_mission_cl.hideMissionPopup();
			var duration:Number = Math.max(2,2*Math.abs(e.currentTarget.no - _current_place_no));
			if(_current_place_no !=0){
				Places(_place_arr[_current_place_no]).closeMission();
			}
			_current_place_no = e.currentTarget.no;
			var x_place_odinal:Number = 0 - _current_place_no*_place_width;
			var x_bg_odinal:Number =0 -_current_place_no*_bg.width/11;		
			if((_bg.width - Math.abs(x_bg_odinal)) < (ValueObject.WIDTH+110)){
				x_bg_odinal = ValueObject.WIDTH+110-_bg.width;
			}
			TweenLite.to( _place_group,duration, { x:x_place_odinal,ease:Quart.easeOut,onComplete:sliderComplete,onCompleteParams:[_current_place_no]} );
			TweenLite.to( _bg,duration, { x:x_bg_odinal,ease:Quart.easeOut} );
		}
		private function sliderComplete(placeId:Number):void{
			if(placeId !=0){
				Places(_place_arr[placeId]).getMission(placeId);
			}
		}
		private function timerHandle(e:TimerEvent):void{
			if(_remain_time >0){
				_remain_time -=1;
				var hh:Number =Math.floor(_remain_time/3600);
				var mm:Number = Math.floor((_remain_time - hh*3600)/60);
				var ss:Number = _remain_time - hh*3600 - mm*60;
				TextField(_control_right_mc.remainTf).text = formatNumber(hh) +":"+formatNumber(mm)+":"+formatNumber(ss);
			}else {
				_timer.stop();
				_timer.removeEventListener(TimerEvent.TIMER,timerHandle);
				_header_cl.showDepositPopup("Đã hết thời gian chơi!");
			}
		}
		private function soundClick(e:MouseEvent):void{
			var sound:MovieClip = e.target as MovieClip;
			if(sound.currentFrame == 1){
				sound.gotoAndStop(2);
				PBE.soundManager.setCategoryMuted("sfx",true);
			}else{
				sound.gotoAndStop(1);
				PBE.soundManager.setCategoryMuted("sfx",false);
			}
			
		}
		private function formatNumber(no:Number):String{
			if(no<10){
				return "0"+no.toString();
			}else{
				return no.toString();
			}
		}
		public function get getControl_left():MovieClip {
			return _control_left_mc;
		}
		public function get pig():MovieClip{
			return _pig;
		}
		public function get getHeader():MovieClip {
			return _get_deposit;
		}
	}
}